<template>
  <div class="job-information-list">
    <go-back title="模版管理" />
    <zk-searcher v-model="query" :options="searchColumns" />
    <w-block class="body" title="工作流程管理" style="margin-top: 10px">
      <template #list>
        <div v-if="canEdit" class="btn-list">
          <el-button
            class="btn-list-item"
            type="primary"
            @click="handleAdd({ template_id: routeId })"
          >增加
          </el-button
          >
          <el-button
            class="btn-list-item"
            type="warning"
            @click="handleUpdate({ template_id: routeId })"
          >修改
          </el-button
          >
          <el-button class="btn-list-item" type="danger" @click="handleDelete"
          >删除
          </el-button
          >
          <el-button
            class="btn-list-item"
            type="default"
            @click="handleRelaSettings"
          >关系设置
          </el-button
          >
        </div>
        <div v-else class="text-info">启动的模版不可编辑</div>
      </template>
      <zk-table
        :columns="tableColumns"
        :service="service"
        :query="query"
        use-selection
        :use-pagination="false"
        :actions="actions"
        :requestInterceptor="requestInterceptor"
        @onSelectionChange="onSelection"
        @doOtherAction="doActions"
        @refresh-data="getRefreshData"
      >
      </zk-table>
    </w-block>
    <w-dialog :visible.sync="visible" height="auto" :title="modalTitle">
      <el-form ref="modelForm" :model="model" label-width="100px">
        <el-row>
          <el-col
            v-for="item of formColumns"
            :key="item.key"
            :span="item.span || 22"
          >
            <el-form-item
              :label="item.label"
              :prop="item.key"
              :rules="
                item.required && [
                  {
                    required: true,
                    message: `请输入${item.label}`,
                    trigger: ['blur'],
                  },
                ]
              "
            >
              <zk-item-pool
                v-model="model[item.key]"
                :option="{ ...item, disabled: item.disabled }"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="flex-end">
          <el-button type="default" @click="visible = false">取 消</el-button>
          <el-button type="primary" @click="submit">保 存</el-button>
        </div>
      </template>
    </w-dialog>
    <!-- 关系设置 -->
    <el-dialog
      :visible.sync="showRelationSetting"
      height="auto"
      @close="dialogClosed"
      width="60%"
      :before-close="dialogDown"
    >
      <template #title>
        <div class="title">
          <span>关系设置</span>
        </div>
      </template>
      <el-row :gutter="16">
        <el-col :span="24">
          <el-col :span="12">
            <el-col :span="24">
              <div style="margin: 0 0 5px 14px">
                <span style="font-size: 16px; text-align: center">&nbsp;</span>
              </div>
            </el-col>
            <el-table
              :data="workList"
              stripe
              @row-click="getWorkSettingList"
              style="cursor: pointer; font-size: 12px"
              row-class-name="row-class-name"
              cell-class-name="cell-class-name"
              header-row-class-name="header-row-class-name"
              header-cell-class-name="header-cell-class-name"
              max-height="400px"
            >
              <el-table-column
                label="工作序号"
                width="80"
                prop="work_idx"
                align="center"
              ></el-table-column>
              <el-table-column
                label="工作名称"
                prop="work_name"
                align="center"
              ></el-table-column>
            </el-table>
          </el-col>
          <el-col :span="12">
            <el-col :span="24">
              <div style="margin: 0 0 5px 14px">
                <span style="font-size: 16px; text-align: center"
                >前置工作</span
                >
              </div>
            </el-col>
            <el-table
              :data="workSettingList"
              stripe
              ref="table"
              @selection-change="handleSelectionChange"
              style="cursor: pointer; font-size: 12px"
              row-class-name="row-class-name"
              cell-class-name="cell-class-name"
              header-row-class-name="header-row-class-name"
              header-cell-class-name="header-cell-class-name"
              max-height="400px"
            >
              <el-table-column
                type="selection"
                width="55"
                align="center"
              ></el-table-column>
              <el-table-column
                label="工作序号"
                width="80"
                prop="work_idx"
                align="center"
              ></el-table-column>
              <el-table-column
                label="工作名称"
                prop="work_name"
                align="center"
              ></el-table-column>
            </el-table>
          </el-col>
        </el-col>
        <el-col :span="24" style="margin-top: 12px; text-align: right">
          <el-button type="primary" size="small" @click="saveForwardWork"
          >保存
          </el-button
          >
          <el-button size="small" @click="closeDialog">关闭</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
  import { TYPE_ENUM } from "@/common/zk-constants"
  import { jobInformationList as service } from "@/services"
  import { templateManagement as templateService } from "@/services"
  import SearchTableCRUDMixin from "@/mixins/search-table-crud-mixin"
  import GoBack from "@/components/go-back"
  import api from "@/api/api"

  const columns = [
    {
      label: "模版名称",
      key: "template_name",
      form: true,
      required: true,
      disabled: true,
    },
    {
      label: "工作序号",
      key: "work_idx",
      type: TYPE_ENUM.NUMBER,
      table: true,
      form: true,
      required: true,
    },
    {
      label: "工作名称",
      key: "work_name",
      search: true,
      table: true,
      form: true,
      required: true,
    },
    {
      label: "前置工作",
      key: "parent_work_idx",
      table: true,
      form: false,
      disabled: true,
    },
    {
      label: "项目阶段",
      key: "app_phase",
      table: true,
      form: true,
      type: TYPE_ENUM.SELECT,
      storeKey: "stage",
      required: true,
    },
    {
      label: "工作类型",
      key: "work_type",
      table: true,
      form: true,
      type: TYPE_ENUM.SELECT,
      storeKey: "jobType",
      required: true,
    },
    {
      label: "责任部门",
      key: "duty_dept",
      search: true,
      type: TYPE_ENUM.SELECT,
      storeKey: "orgList",
    },
    {
      label: "责任部门",
      key: "duty_dept_name",
      table: true,
      storeKey: "orgList",
    },
    { label: "完成时限", key: "dur_time", table: true, type: TYPE_ENUM.NUMBER },
  ]

  const actions = [{ classname: "primary", text: "任务配置", type: "manager" }]
  export default {
    mixins: [SearchTableCRUDMixin],
    components: { GoBack },
    data() {
      return {
        routeId: this.$route.params.id,
        columns,
        service,
        actions,
        showRelationSetting: false,
        workList: [],
        workSettingList: [],
        param: {
          id: "",
          priorIds: "",
        },
        work_idx: "",
        idx: [],
        allWorkList: [],
        idList: [],
        parentIdList: [],
        startId: "",
        isOk: true,
        isStart: 1,
        isStart1: 1,
        template_id: this.$route.params.id,
        template_name: null,
        canEdit: false
      }
    },
    computed: {
      modalTitle() {
        return this.isAddModal ? "添加" : "编辑"
      },
    },
    watch: {
      model(newModel) {
        newModel.template_name = this.template_name
      }
    },
    created() {
      this.getCurrentTemplateInfo()
    },
    methods: {
      async getCurrentTemplateInfo() {
        const { list: [template] = [] } = await templateService.getList({ id: this.routeId }) || {}
        this.template_name = template.template_name
        this.model.template_name = this.template_name
        this.canEdit = !(template.is_start === 1)
      },
      //删除判断
      handleDelete(model = {}) {
        //   console.log(this.selectedRows);
        //   debugger;
        if (sessionStorage.getItem("is_start") == 1) {
          this.$message({
            message: "启用模板不能删除工作",
            type: "warning",
          })
          return
        }

        if (this.selectedRows.length > 0) {
          var work_idx = this.selectedRows[0].work_idx
          var parent_work_idx = ""
          for (var i = 0; i < this.allWorkList.length; i++) {
            parent_work_idx = this.allWorkList[i].parent_work_idx
            if (parent_work_idx != undefined) {
              var arr = parent_work_idx.split("")
              //   console.log(arr)
              for (var j = 0; j < arr.length; j++) {
                //   console.log(arr[i]);
                if (work_idx == arr[j]) {
                  this.$message({
                    message: "前置工作不能先行删除",
                    type: "warning",
                  })
                  return
                }
              }
            }
          }
        }

        //   debugger;
        if (this.selectedRows.length) {
          this.$alert(`确认删除 ${this.selectedRows.length} 条记录`, "确认删除", {
            confirmButtonText: "确定",
            callback: async (action) => {
              console.log(action)
              if (action === "confirm") {
                const ids = this.selectedRows.map((e) => e.id).join(";");
                (await this.service.delItemByIds(ids)) && this.reload()
              }
            },
          })
        } else {
          this.$message.warning("请选择要删除的记录")
        }
      },
      getRefreshData({ tableData }) {
        //   console.log("getRefreshData", tableData);
        this.allWorkList = tableData
        //   console.log(this.allWorkList);
        tableData.forEach((item) => {
        })
      },
      async doActions({ row: { id } = {}, type }) {
        type === "manager" && this.$router.push(`/task-configuration/${id}`)
      },
      //点击关系设置按钮
      async handleRelaSettings() {
        // todo 关系设置按钮
        this.showRelationSetting = true
        api.get["/rest/rptWork/queryWorkList"](this.template_id).then(
          ({ data }) => {
            if (!data) return
            // console.log(data)
            this.workList = data.data
          }
        )
      },
      //关闭弹窗
      dialogClosed() {
        this.showRelationSetting = false
        this.param.id = ""
        this.param.priorIds = ""
        this.isStart = 1
        this.isStart1 = 1
      },
      //右侧表格复选框
      handleSelectionChange(val) {
        this.idx = val
        // console.log(val);
        //   if (val.length == 0) {
        this.param.priorIds = ""
        this.isStart = 1
        this.isStart1 = 1
        //   }
        for (var i = 0; i < val.length; i++) {
          //   debugger;
          if (i == val.length - 1) {
            this.param.priorIds = this.param.priorIds + val[i].id
          } else {
            this.param.priorIds = this.param.priorIds + val[i].id + ";"
          }
        }
        //   console.log(this.param.priorIds);
      },
      //点击左侧表格获取右边表格数据
      getWorkSettingList(row) {
        this.work_idx = row.work_idx
        this.param.id = ""
        this.param.priorIds = ""
        //   console.log(row)
        this.param.id = row.id
        // console.log(this.param.id)
        api.get["/rest/rptWork/queryPriorWorkList"](
          row.id,
          this.template_id
        ).then(({ data }) => {
          if (!data) return
          // console.log(data)
          this.workSettingList = data.data
          // for (var i = 0; i < data.data.length; i++) {
          //   if (data.data[i].is_prior == 1) {
          //     this.idx.push(data.data.work_idx);
          //   }
          // }
          this.$nextTick(() => {
            this.toggleSelection(this.workSettingList)
          })
        })
      },
      //右侧表格默认选中方法
      toggleSelection(rows) {
        if (rows) {
          // console.log(rows)
          rows.forEach((row) => {
            //设置该行选中
            // console.log(row)
            //   this.startId = row.work_idx;
            if (row.is_prior == 1) {
              this.$refs.table.toggleRowSelection(row)
            }
          })
        } else {
          this.$refs.table.clearSelection(row)
        }
      },
      //判断工作是否为闭环
      isCircle() {
        for (let m = 0; m < this.allWorkList.length; m++) {
          for (let n = 0; n < this.parentIdList.length; n++) {
            if (this.allWorkList[m].work_idx == this.parentIdList[n]) {
              if (this.allWorkList[m].parent_work_idx != undefined) {
                let arr1 = this.allWorkList[m].parent_work_idx.split("")
                for (let o = 0; o < arr1.length; o++) {
                  if (this.work_idx == arr1[o]) {
                    if (this.isStart1 == 1)
                      this.$message({
                        message:
                          this.startId +
                          "号不能设置为" +
                          this.work_idx +
                          "号的前置工作",
                        type: "warning",
                      })
                    this.isStart1++
                    return false
                  }
                }
                this.parentIdList = arr1
                this.isCircle()
              }
            }
          }
        }
      },
      //保存
      saveForwardWork() {
        if (this.param.id == "" || this.param.id == null) {
          this.$message({
            message: "请先选择左侧表格的工作",
            type: "warning",
          })
          return
        }

        //   console.log(this.allWorkList);
        //   console.log(this.workSettingList)
        //   console.log(this.workList)
        //   console.log(this.idx);

        //   console.log(this.work_idx);
        this.isOk = true
        this.isStart1 = 1
        this.isStart = 1

        for (let i = 0; i < this.allWorkList.length; i++) {
          for (let j = 0; j < this.idx.length; j++) {
            if (this.allWorkList[i].work_idx == this.idx[j].work_idx) {
              if (this.allWorkList[i].parent_work_idx != undefined) {
                //   console.log(
                //     this.allWorkList[i].parent_work_idx.replace(/【|】/g, "")
                //   );
                var arr = this.allWorkList[i].parent_work_idx.split("")
                for (let k = 0; k < arr.length; k++) {
                  this.startId = this.idx[j].work_idx
                  if (this.work_idx == arr[k]) {
                    if (this.isStart == 1)
                      this.$message({
                        message:
                          this.idx[j].work_idx +
                          "号不能设置为" +
                          this.work_idx +
                          "号的前置工作",
                        type: "warning",
                      })
                    this.isStart++
                    return
                  }
                }
                this.parentIdList = arr
                if (this.isCircle() == false) {
                  this.isOk = false
                  return
                }
              }
            }
          }
        }
        if (this.isOk)
          api.post["/rest/rptWork/doWorkInsertPrior"](
            this.param.id,
            this.param.priorIds
          ).then(({ data }) => {
            if (!data) return
            // console.log(this.param.id)
            // console.log(this.param.priorIds)
            this.reload()
            // this.workSettingList = [];
            this.$message({
              message: "保存成功",
              type: "success",
            })
            // this.showRelationSetting = false;
            // this.workSettingList = data.data;
          })
      },
      //关闭
      closeDialog() {
        this.workSettingList = []
        this.showRelationSetting = false
        this.param.id = ""
        this.param.priorIds = ""
      },
      dialogDown() {
        this.workSettingList = []
        this.showRelationSetting = false
        this.param.id = ""
        this.param.priorIds = ""
      },
      requestInterceptor(query) {
        return { ...query, template_id: this.routeId }
      },
      async queryPriorWorkList() {
        return await this.service.queryPriorWorkList({
          id: "",
          template_id: this.routeId,
        })
      },
    },
  }
</script>
<style scoped lang="scss">
  .title {
    $h: 30px;
    width: 100%;
    height: $h;
    line-height: $h;
    font-size: 16px;
    font-weight: 400;
    color: #464646;
    border-bottom: 1px solid rgba(77, 116, 251, 0.3);

    > span {
      display: inline-block;
      padding: 0 4px;
      height: $h;
      line-height: $h;
      border-bottom: 2px solid rgba(62, 96, 251, 1);
    }
  }
</style>
